package searcher.gui;

import java.io.File;
import java.io.FileFilter;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * A javax.swing.tree.TreeModel that allows a view of a file system
 * 
 * @version $Id: FileTreeModel.java,v 1.1 2006/04/05 14:14:42 abutler Exp $
 */
public class FileTreeModel implements TreeModel
{
	private final File theRoot;

	private FileFilter theFilter;

	private java.util.List<TreeModelListener> theModelListeners;

	/**
	 * Creates a FileTreeModel with a view to the entire file system
	 * 
	 * @param filter The file filter determining which files to show
	 */
	public FileTreeModel(FileFilter filter)
	{
		this(null, filter);
	}

	/**
	 * Creates a FileTreeModel with a view rooted at a given file
	 * 
	 * @param root The root of the view
	 * @param filter The file filter determining which files to show
	 */
	public FileTreeModel(File root, FileFilter filter)
	{
		theRoot = root;
		theFilter = filter;
		theModelListeners = new java.util.ArrayList<TreeModelListener>();
	}

	public Object getRoot()
	{
		return theRoot;
	}

	public int getChildCount(Object parent)
	{
		if(theRoot == null)
			return File.listRoots().length;
		File [] children = getChildren(parent);
		if(children != null)
			return children.length;
		else
			return 0;
	}

	public boolean isLeaf(Object node)
	{
		if(!(node instanceof File))
			return false;
		return !((File) node).isDirectory();
	}

	public void addTreeModelListener(TreeModelListener l)
	{
		theModelListeners.add(l);
	}

	public void removeTreeModelListener(TreeModelListener l)
	{
		theModelListeners.remove(l);
	}

	/**
	 * Gets the file children of a file (directory or zip file)
	 * 
	 * @param parent The parent directory or zip file to query for children
	 * @return The children files of <code>parent</code>
	 */
	public File [] getChildren(Object parent)
	{
		if(!(parent instanceof File))
			return null;
		File p = (File) parent;
		if(theFilter == null)
			return p.listFiles();
		else
			return p.listFiles(theFilter);
	}

	public Object getChild(Object parent, int index)
	{
		File [] children = getChildren(parent);
		if(children != null && children.length > index)
			return children[index];
		return null;
	}

	public int getIndexOfChild(Object parent, Object child)
	{
		File [] children = getChildren(parent);
		if(children == null)
			return -1;
		for(int i = 0; i < children.length; i++)
		{
			if(children[i].equals(child))
				return i;
		}
		return -1;
	}

	public void valueForPathChanged(TreePath path, Object newValue)
	{
		System.out.println("No implementation for changing tree structure");
	}
}
